package com.ceba.test.modules.storage.logicService;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ceba.base.web.response.IResult;
import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.enums.CopyFlagEnum;
import com.ceba.test.base.enums.StorageStatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ceba.test.base.enums.ResultStatusEnum;
import com.ceba.test.base.language.ResourceUtils;

import com.ceba.test.modules.storage.cache.GStorageAddressCache;
import com.ceba.test.modules.storage.entity.GStorageAddress;

import com.ceba.test.modules.storage.service.GStorageAddressService;

import abc.ID;
public class GStorageAddressLogicService {
	private GStorageAddressService gStorageAddressService;
	private static Logger logger = LoggerFactory.getLogger(GStorageAddressLogicService.class);
	
	/**
	 * 
	 * @param gStorageAddress
	 * @param dic
	 * @return
	 */
	public String list(GStorageAddress gStorageAddress,Map<String, Object> dic){
		JSONObject jsonObject=gStorageAddressService.list(gStorageAddress,dic);
		return jsonObject.toString();		
	}
	/**
	 * 查询所有
	 * @return
	 */
	public List<GStorageAddress> sreachAll() {
		return gStorageAddressService.sreachAll();
	}
	/**
	 * 查询
	 * @param //GStorageAddress 对象
	 * @return
	 */
	public IResult sreach(GStorageAddress gStorageAddress){
		IResult iResult = new IResult();
		if(gStorageAddress == null || StringUtils.isEmpty(gStorageAddress.getId())){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_DATA_ALL_PLEASE=请完善查询条件
			String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_ALL_PLEASE");
			iResult.setMessage(message);
			return iResult;
		}
		GStorageAddress _gStorageAddress=gStorageAddressService.sreach(gStorageAddress.getId());
		if(_gStorageAddress == null){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_DATA_NOT_EMPTY=查询的文件存储地址不存在
			String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_NOT_EMPTY");
			iResult.setMessage(message);
			return iResult;
		}
		iResult.setResultCode(ResultStatusEnum.CG.getCode());
		iResult.setData(_gStorageAddress);
		return iResult;
	}

	
	/**
	 * 编辑
	 * @param //GStorageAddress 对象
	 * @return
	 */
	public IResult edit(GStorageAddress gStorageAddress){
		IResult iResult = new IResult();
		GStorageAddress _gStorageAddress=null;
		if(gStorageAddress == null || StringUtils.isEmpty(gStorageAddress.getId())){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_DATA_EDIT_PLEASE=请完善编辑条件
			String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_EDIT_PLEASE");
			iResult.setMessage(message);
			return iResult;
		}
		
		long usable=gStorageAddress.getFile().getUsableSpace()/(1024*1024);
		iResult=isDirectory(gStorageAddress);
		if( iResult != null){
			return iResult;
		}else{
			iResult = new IResult();
		}
		if(StringUtils.equals(gStorageAddress.getStatus(), StorageStatusEnum.CAN.getCode())){
			//可用状态下  文件路径被重新编辑了
			_gStorageAddress=gStorageAddressService.sreach(gStorageAddress.getId());
			//如果文件路径修改了
			if(!StringUtils.equals(gStorageAddress.getFile().getPath(), _gStorageAddress.getPath())){
				if(!isDirCopy(_gStorageAddress.getId(),gStorageAddress.getPath(),_gStorageAddress.getPath())){
					iResult.setResultCode(ResultStatusEnum.SB.getCode());
					//STORAGE_SREACH_COPY_PATH_CHANGE=請將文件拷貝到此目錄后更改
					String message=ResourceUtils.getMessage("STORAGE_SREACH_COPY_PATH_CHANGE");
					iResult.setMessage(message);
					return iResult;
				}
			}
		}
		long total=gStorageAddress.getCapacity();//M
		if(total > usable){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_CAPACITY_NO=当前磁盘可使用空间不够
			String message=ResourceUtils.getMessage("STORAGE_SREACH_CAPACITY_NO");
			iResult.setMessage(message);
			return iResult;
		}
		gStorageAddress.setActualSize(usable);
		if(!StringUtils.equals(gStorageAddress.getStatus(), StorageStatusEnum.CAN.getCode())){
			gStorageAddress.setRest(total);
		}else{
			//可用状态  剩余空间  是否 大于  实际 可用空间
			if(gStorageAddress.getActualSize() < gStorageAddress.getRest() && _gStorageAddress.getRest() != gStorageAddress.getRest()){
				iResult.setResultCode(ResultStatusEnum.SB.getCode());
				//STORAGE_SREACH_CAPACITY_NO=当前磁盘可使用空间不够
				String message=ResourceUtils.getMessage("STORAGE_SREACH_CAPACITY_NO");
				iResult.setMessage(message);
				return iResult;
			}
		}
		boolean bool = gStorageAddressService.edit(gStorageAddress);
		if(!bool){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_DATA_SAVE_FAIL=保存失败
			String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_SAVE_FAIL");
			iResult.setMessage(message);
			return iResult;
		}
		iResult.setResultCode(ResultStatusEnum.CG.getCode());
		//STORAGE_SREACH_DATA_SAVE_SUCCESS=保存成功
		String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_SAVE_SUCCESS");
		iResult.setMessage(message);
		iResult.set("rest",gStorageAddress.getRest());
		//更新一下缓存
		againCache();
		return iResult;
	}

	/**
	 * 判断新路径 下是否有  此存储地址所对应的  文件
	 * @param id
	 * @param newPath
	 * @return
	 */
	private boolean isDirCopy(String id, String newPath,String oldPath) {
		List<String> virtualList=new ArrayList<>();
		//随机签名文件
		List<String> signList=gStorageAddressService.randSignFile(id);
		if(CollectionUtils.isNotEmpty(signList)){
			virtualList.addAll(signList);
		}
		//随机主文件
		List<String> mailList=gStorageAddressService.randMailFile(id);
		if(CollectionUtils.isNotEmpty(mailList)){
			virtualList.addAll(mailList);
		}
		//随机附件
		List<String> attachList=gStorageAddressService.randAttachFile(id);
		if(CollectionUtils.isNotEmpty(attachList)){
			virtualList.addAll(attachList);
		}
		//表中 stamp 对应的文件
		List<String> stampList=gStorageAddressService.randStampFile(id);
		if(CollectionUtils.isNotEmpty(stampList)){
			virtualList.addAll(stampList);
		}
		//模板文件判断是否存在
		List<String> templatesList=gStorageAddressService.randTemplatesFile(id);
		if(CollectionUtils.isNotEmpty(templatesList)){
			virtualList.addAll(templatesList);
		}
		
		if(CollectionUtils.isNotEmpty(virtualList)){
			for(String path:virtualList){
				if(!new File(newPath+"/"+path).exists()){
					return false;
				}
			}
		}
		
		//非表中文件是否存在
		List<String> virtualPathList= CebaPathUtil.getNeedCopyDir();
		for(String path:virtualPathList){
			if(!new File(newPath+path).exists()  && new File(oldPath+path).exists()){
				return false;
			}
		}
		return true;
	}

	/**
	 * 添加
	 * @param //GStorageAddress 对象
	 * @return
	 */
	public IResult add(GStorageAddress gStorageAddress){
		IResult iResult = new IResult();
		if(gStorageAddress == null){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_DATA_ADD_PLEASE=请完善新增条件
			String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_ADD_PLEASE");
			iResult.setMessage(message);
			return iResult;
		}
		gStorageAddress.setId(ID.getGuid());
		iResult=isDirectory(gStorageAddress);
		if( iResult != null){
			return iResult;
		}else{
			iResult = new IResult();
		}
		File file=new File(gStorageAddress.getPath());
		//判断磁盘剩余容量  与  总容量一致
		long totalSpace = file.getTotalSpace() / 1024 / 1024;		//总空间，单位M
		long freeSpace = file.getUsableSpace() / 1024 / 1024;		//可用空间，单位M
		long usedSpace = (file.getTotalSpace() - file.getUsableSpace()) / 1024 / 1024;	//已用空间，单位M
		gStorageAddress.setCopyFlag(CopyFlagEnum.NOCOPY.getCode());
		gStorageAddress.setStatus(StorageStatusEnum.NOSTART.getCode());
		if(freeSpace < CebaConfig.FILE_STORAGE_CHANGE_VALUE){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_CAPACITY_NO=当前磁盘可使用空间不够
			String message=ResourceUtils.getMessage("STORAGE_SREACH_CAPACITY_NO");
			iResult.setMessage(message);
			return iResult;
		}
		
		//过滤器
		gStorageAddress.setId(ID.getGuid());
		gStorageAddress.setFilter(gStorageAddress.getFilterStr());

		gStorageAddress.setCapacity(totalSpace);
		gStorageAddress.setActualSize(usedSpace);
		gStorageAddress.setRest(freeSpace);

		boolean bool = gStorageAddressService.add(gStorageAddress);
		if(!bool){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_DATA_ADD_FAIL=新增失败
			String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_ADD_FAIL");
			iResult.setMessage(message);
			return iResult;
		}
		iResult.setResultCode(ResultStatusEnum.CG.getCode());
		//STORAGE_SREACH_DATA_ADD_SUCCESS=新增成功
		String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_ADD_SUCCESS");
		iResult.setMessage(message);
		againCache();
		return iResult;
	}
	
	private IResult isDirectory(GStorageAddress gStorageAddress){
		IResult iResult = new IResult();
		File file=gStorageAddress.getFile();
		if(!file.exists()){
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_SREACH_DATA_NO_PATH=系统没有此文件夹
			String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_NO_PATH");
			iResult.setMessage(message);
			return iResult;
		}else{
			if(!file.isDirectory()){
				iResult.setResultCode(ResultStatusEnum.SB.getCode());
				//STORAGE_SREACH_DATA_NO_PATH=系统没有此文件夹
				String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_NO_PATH");
				iResult.setMessage(message);
				return iResult;
			}else{
				//判断此目录是否被使用过
				gStorageAddress.setPath(file.getPath());
				long count=gStorageAddressService.sreachPath(gStorageAddress.getId(),file.getPath(),gStorageAddress.getName());
				//在编辑的情况下不能有两个相同的目录
				if(count > 0){
					iResult.setResultCode(ResultStatusEnum.SB.getCode());
					//STORAGE_SREACH_DATA_NO_USE=名称或目录重复，请重新输入
					String message=ResourceUtils.getMessage("STORAGE_SREACH_DATA_NO_USE");
					iResult.setMessage(message);
					return iResult;
				}
			}
		}
		
		return null;
	}
	
	private void perfectStorageAddress(GStorageAddress gStorageAddress){
		//1.确定过滤器标识
		
		
		
		/*private String filter;//过滤路径
		private String path;//磁盘路径
		private long capacity;//文件允许存储大小   单位 M
		private long actualSize;//磁盘实际剩余大小  当前存储文件夹  相对于 磁盘总容量
		private long rest;//剩余大小   相对于 capacity字段
		private String copyFlag;//是否拷贝  1 为拷贝  2 已拷贝  默认 1  CopyFlagEnum
		private String status;//状态 1 未开启 2可用  3已满 默认1		StorageStatusEnum*/
    }

	public GStorageAddressService getgStorageAddressService() {
		return gStorageAddressService;
	}


	public void setgStorageAddressService(GStorageAddressService gStorageAddressService) {
		this.gStorageAddressService = gStorageAddressService;
	}

	/**
	 * 查询出已拷贝状态的存储地址
	 * @return
	 */
	public GStorageAddress searchCopiedAddress() {
		return this.gStorageAddressService.searchCopiedAddress();
	}

	/**
	 * 删除
	 * @param gStorageAddress
	 * @return
	 */
	public IResult delete(GStorageAddress gStorageAddress) {
		IResult iResult=new IResult();
		boolean bool=gStorageAddressService.delete(gStorageAddress.getId());
		if(bool){
			iResult.setResultCode(ResultStatusEnum.CG.getCode());
			//STORAGE_DELETE_SUCCEC=删除成功
			iResult.setMessage(ResourceUtils.getMessage("STORAGE_DELETE_SUCCEC"));
			//更新一下缓存
			againCache();
		}else{
			iResult.setResultCode(ResultStatusEnum.SB.getCode());
			//STORAGE_DELETE_FLAI=删除失败
			iResult.setMessage(ResourceUtils.getMessage("STORAGE_DELETE_FLAI"));
		}
		return iResult;
	}
	
	public long totalCount(){
		return gStorageAddressService.totalCount();
	}
	
	public void editCopyFlag(String id, String code) {
		gStorageAddressService.editCopyFlag(id, code);
	}
	public void editStatus(String id, String code) {
		gStorageAddressService.editStatus(id, code);
		
	}
	private void againCache(){
		List<GStorageAddress> list=sreachAll();
		GStorageAddressCache.againAllData(list);
	}
	
	public static void main(String[] args) {
		File win = new File("C:\\");  
        System.out.println(win.getPath());  
        System.out.println(win.getName());  
        System.out.println("自由 space = " + win.getFreeSpace());  
        System.out.println("可用 Usable space = " + win.getUsableSpace());  
        System.out.println("Total space = " + win.getTotalSpace());  
        System.out.println();  
	}

	/**
	 * 更新路径
	 * @param id
	 * @param value
	 */
	public void updatePath(String id,String value){
		gStorageAddressService.updatePath(id,value);
	}

}
